package com.cn.spjdbc;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class BaseDao<ID extends Serializable> extends JdbcDaoSupport {
	protected Class<ID> idClass;
	
	protected Class<ID> getIdClass() {
		if (idClass == null) {
			idClass = (Class<ID>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		}
		return idClass;
	}
	@Autowired
	protected void setDatasource(DataSource dataSource) {
		super.setDataSource(dataSource);
	}

	protected ID insert(final String sql,final Object...params) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		this.getJdbcTemplate().update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				for (int i=0;i<params.length;i++) {
					ps.setObject(i+1,params[i]);
				}
				return ps;
			}
		},keyHolder);
		return TransformKeyTool.getId(keyHolder, getIdClass());
	}
	
}
